<template>
  <div v-if="isVisible" class="screenshot-container" tabindex="0" @keydown.capture="handleKeyDown">
    <!-- 简单的 Loading 提示 (暂时注释) -->
    <!-- <div v-if="isLoading" class="loading-hint">
      正在加载截图...
    </div> -->
    
    <!-- 画布编辑区域 - 显示原始截图 -->
    <canvas
      ref="canvasRef"
      class="screenshot-canvas"
      @mousedown="handleMouseDown"
      @mousemove="handleMouseMove"
      @mouseup="handleMouseUp"
    ></canvas>

    <!-- 选区 -->
    <div
      v-if="selectionRect"
      class="screenshot-selection"
      :style="selectionStyle"
    >
      <!-- 选区尺寸提示 -->
      <div class="selection-info">
        {{ Math.abs(selectionRect.width) }} × {{ Math.abs(selectionRect.height) }}
      </div>

      <!-- 工具栏 -->
      <div v-if="isSelectionComplete" class="toolbar-wrapper" :style="toolbarStyle">
        <ScreenshotToolbar
          @tool-select="handleToolSelect"
          @save="handleSave"
          @copy="handleCopy"
          @cancel="handleCancel"
          @ocr="handleOCR"
        />
      </div>
    </div>

    <!-- OCR 结果对话框 -->
    <OCRResultDialog
      :visible="ocrDialogVisible"
      :text="ocrResultText"
      :confidence="ocrConfidence"
      @close="ocrDialogVisible = false"
      @copy="handleOCRCopy"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import ScreenshotToolbar from './ScreenshotToolbar.vue'
import OCRResultDialog from './OCRResultDialog.vue'
import { CanvasEditor } from '@/utils/screenshot/canvasEditor'
import { saveService } from '@/utils/screenshot/saveService'
import { ocrService } from '@/utils/screenshot/ocrService'
import { toast } from '@/utils/toast'
import type { AnnotationType } from '@/types/screenshot'

const isVisible = ref(false)
// const isLoading = ref(false) // 图片加载状态 (暂时注释)
const canvasRef = ref<HTMLCanvasElement | null>(null)
const editor = ref<CanvasEditor | null>(null)

const selectionRect = ref<{ x: number; y: number; width: number; height: number } | null>(null)
const isSelecting = ref(false)
const isSelectionComplete = ref(false)
const startPoint = ref<{ x: number; y: number } | null>(null)
const screenImageData = ref<string>('')

// OCR 相关状态
const ocrDialogVisible = ref(false)
const ocrResultText = ref('')
const ocrConfidence = ref(0)

// 选区样式
const selectionStyle = computed(() => {
  if (!selectionRect.value) return {}

  const { x, y, width, height } = selectionRect.value
  return {
    left: `${Math.min(x, x + width)}px`,
    top: `${Math.min(y, y + height)}px`,
    width: `${Math.abs(width)}px`,
    height: `${Math.abs(height)}px`,
  }
})

// 工具栏样式
const toolbarStyle = computed(() => {
  if (!selectionRect.value) return {}

  const { x, y, width, height } = selectionRect.value
  const normalizedX = Math.min(x, x + width)
  const normalizedY = Math.min(y, y + height)
  const normalizedWidth = Math.abs(width)
  const normalizedHeight = Math.abs(height)
  
  // 工具栏显示在选区底部
  return {
    position: 'fixed',
    left: `${normalizedX + normalizedWidth / 2}px`,
    top: `${normalizedY + normalizedHeight + 10}px`,
    transform: 'translateX(-50%)',
    zIndex: 10000,
  }
})

// 初始化
const initialize = async (imageData: string) => {
  console.log('初始化截图，数据长度:', imageData?.length || 0)
  
  // 开始加载 (暂时注释)
  // isLoading.value = true
  
  // 清理所有旧的 Toast
  toast.clear()
  
  screenImageData.value = imageData
  isVisible.value = true
  isSelectionComplete.value = false
  selectionRect.value = null

  await nextTick()

  if (canvasRef.value && imageData) {
    const canvas = canvasRef.value
    
    // 重置 canvas 位置
    canvas.style.left = '0'
    canvas.style.top = '0'
    canvas.style.position = 'fixed'
    
    // 先加载图片获取真实尺寸
    const img = new Image()
    img.onload = () => {
      console.log('图片加载成功，尺寸:', img.width, 'x', img.height)
      
      // 设置 canvas 尺寸为图片实际尺寸
      canvas.width = img.width
      canvas.height = img.height
      
      // 绘制屏幕截图
      const ctx = canvas.getContext('2d')
      if (ctx) {
        ctx.drawImage(img, 0, 0, img.width, img.height)
        console.log('截图绘制完成')
      }
      
      // 加载完成，关闭 Loading (暂时注释)
      // isLoading.value = false
      console.log('截图已就绪，可以开始操作')
    }
    img.onerror = (error) => {
      console.error('图片加载失败:', error)
      // isLoading.value = false
      toast.error('截图加载失败，请重试', 2000)
    }
    img.src = imageData
  } else {
    console.error('Canvas 或图片数据不存在')
    // isLoading.value = false
  }
}

// 获取相对于 canvas 的坐标
const getCanvasPosition = (e: MouseEvent): { x: number; y: number } => {
  if (!canvasRef.value) return { x: 0, y: 0 }
  
  const rect = canvasRef.value.getBoundingClientRect()
  return {
    x: e.clientX - rect.left,
    y: e.clientY - rect.top
  }
}

// 鼠标按下
const handleMouseDown = (e: MouseEvent) => {
  // Loading 时禁止操作 (暂时注释)
  // if (isLoading.value) {
  //   console.log('截图正在加载中，请稍候...')
  //   return
  // }
  
  if (!isSelectionComplete.value) {
    isSelecting.value = true
    const pos = getCanvasPosition(e)
    startPoint.value = pos
    selectionRect.value = {
      x: pos.x,
      y: pos.y,
      width: 0,
      height: 0,
    }
    console.log('开始选择:', pos)
  }
}

// 鼠标移动
const handleMouseMove = (e: MouseEvent) => {
  if (isSelecting.value && startPoint.value && selectionRect.value) {
    const pos = getCanvasPosition(e)
    selectionRect.value.width = pos.x - startPoint.value.x
    selectionRect.value.height = pos.y - startPoint.value.y
  }
}

// 鼠标抬起
const handleMouseUp = async (e: MouseEvent) => {
  if (isSelecting.value && selectionRect.value) {
    isSelecting.value = false

    // 如果选区太小，则忽略
    if (Math.abs(selectionRect.value.width) < 10 || Math.abs(selectionRect.value.height) < 10) {
      selectionRect.value = null
      return
    }

    isSelectionComplete.value = true

    // 裁剪选区并初始化编辑器
    await initializeEditor()
  }
}

// 初始化编辑器
const initializeEditor = async () => {
  if (!canvasRef.value || !selectionRect.value) return

  const { x, y, width, height } = selectionRect.value
  const normalizedX = Math.min(x, x + width)
  const normalizedY = Math.min(y, y + height)
  const normalizedWidth = Math.abs(width)
  const normalizedHeight = Math.abs(height)

  console.log('裁剪区域:', {
    x: normalizedX,
    y: normalizedY,
    width: normalizedWidth,
    height: normalizedHeight
  })

  // 创建新的 canvas 用于编辑
  const editCanvas = document.createElement('canvas')
  editCanvas.width = normalizedWidth
  editCanvas.height = normalizedHeight

  const ctx = editCanvas.getContext('2d')
  if (!ctx) return

  // 复制选区内容
  const sourceCtx = canvasRef.value.getContext('2d')
  if (!sourceCtx) return

  const imageData = sourceCtx.getImageData(
    normalizedX,
    normalizedY,
    normalizedWidth,
    normalizedHeight
  )
  ctx.putImageData(imageData, 0, 0)

  // 更新主 canvas 位置和尺寸
  const canvas = canvasRef.value
  canvas.style.left = `${normalizedX}px`
  canvas.style.top = `${normalizedY}px`
  canvas.width = normalizedWidth
  canvas.height = normalizedHeight
  
  const mainCtx = canvas.getContext('2d')
  if (mainCtx) {
    mainCtx.drawImage(editCanvas, 0, 0)
  }

  console.log('Canvas 位置:', {
    left: canvas.style.left,
    top: canvas.style.top,
    width: canvas.width,
    height: canvas.height
  })

  // 创建编辑器
  editor.value = new CanvasEditor(canvasRef.value)
  await editor.value.setBackgroundImage(editCanvas.toDataURL())
}

// 键盘事件
const handleKeyDown = (e: KeyboardEvent) => {
  console.log('按键:', e.key, e.code) // 调试用
  
  if (e.key === 'Escape' || e.code === 'Escape') {
    e.preventDefault()
    e.stopPropagation()
    handleCancel()
  } else if (e.key === 'Enter' && isSelectionComplete.value) {
    e.preventDefault()
    handleSave()
  } else if (e.ctrlKey && e.key === 'z') {
    e.preventDefault()
    editor.value?.undo()
  } else if (e.ctrlKey && e.key === 'y') {
    e.preventDefault()
    editor.value?.redo()
  }
}

// 工具选择
const handleToolSelect = (tool: AnnotationType) => {
  editor.value?.setTool(tool)
}

// 保存
const handleSave = async () => {
  console.log('保存截图')
  
  if (!canvasRef.value) {
    toast.warning('没有可保存的内容')
    return
  }

  try {
    // 直接从 canvas 导出
    const dataUrl = canvasRef.value.toDataURL('image/png')
    console.log('导出图片，数据长度:', dataUrl.length)
    
    if (window.electronAPI) {
      // Electron 环境，使用文件保存对话框
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')
      const filename = `Screenshot_${year}${month}${day}_${hours}${minutes}${seconds}.png`
      
      console.log('准备保存，文件名:', filename)
      
      // 先关闭截图窗口，让用户能看到保存对话框
      console.log('关闭截图窗口，准备显示保存对话框')
      window.electronAPI.closeScreenshot()
      
      // 异步保存（窗口已关闭，不影响用户操作）
      const result = await window.electronAPI.saveScreenshot(dataUrl, filename)
      
      console.log('保存结果:', result)
      
      // 保存完成后的处理（窗口已经关闭了，这里只是日志）
      if (result.canceled) {
        console.log('用户取消了保存')
      } else if (result.success) {
        console.log('保存成功:', result.path)
      } else {
        console.error('保存失败:', result.error)
      }
    } else {
      // 浏览器环境，直接下载
      const link = document.createElement('a')
      link.download = `Screenshot_${Date.now()}.png`
      link.href = dataUrl
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      toast.success('下载成功！')
      handleCancel()
    }
  } catch (error) {
    console.error('保存失败:', error)
    toast.error(`保存失败：${error}`, 3000)
  }
}

// 复制
const handleCopy = async () => {
  console.log('复制到剪贴板')
  
  if (!canvasRef.value) {
    toast.warning('没有可复制的内容')
    return
  }

  try {
    const dataUrl = canvasRef.value.toDataURL('image/png')
    console.log('准备复制，数据长度:', dataUrl.length)
    
    if (window.electronAPI) {
      // Electron 环境，使用原生剪贴板
      const result = await window.electronAPI.copyToClipboard(dataUrl)
      
      if (result.success) {
        console.log('复制成功')
        toast.success('已复制到剪贴板！')
        handleCancel()
      } else {
        console.error('复制失败:', result.error)
        toast.error(`复制失败：${result.error || '未知错误'}`, 3000)
      }
    } else {
      // 浏览器环境，使用 Clipboard API
      const blob = await fetch(dataUrl).then(r => r.blob())
      await navigator.clipboard.write([
        new ClipboardItem({ 'image/png': blob })
      ])
      
      toast.success('已复制到剪贴板！')
      handleCancel()
    }
  } catch (error) {
    console.error('复制失败:', error)
    toast.error(`复制失败：${error}`, 3000)
  }
}

// 取消
const handleCancel = () => {
  console.log('取消截图')
  
  isVisible.value = false
  isSelectionComplete.value = false
  selectionRect.value = null
  startPoint.value = null

  if (editor.value) {
    editor.value.destroy()
    editor.value = null
  }

  // 通知主进程关闭截图窗口
  if (window.electronAPI) {
    console.log('通知主进程关闭窗口')
    window.electronAPI.closeScreenshot()
  } else {
    // 如果不在 Electron 环境，返回主页
    console.log('返回主页')
    window.location.hash = '#/'
  }
}

// OCR 识别
const handleOCR = async () => {
  if (!canvasRef.value) {
    toast.warning('请先完成截图选择')
    return
  }

  try {
    // 选区完成后，canvas 已经是裁剪后的内容，直接使用
    const canvas = canvasRef.value
    console.log('OCR 识别 Canvas 尺寸:', canvas.width, 'x', canvas.height)
    
    // 检查 canvas 尺寸
    if (canvas.width === 0 || canvas.height === 0) {
      toast.error('截图区域无效，请重新选择')
      return
    }

    const dataUrl = canvas.toDataURL('image/png')
    console.log('开始 OCR 识别，图片数据长度:', dataUrl.length)

    // 显示加载提示（OCR 可能需要较长时间，但不要太久）
    toast.info('正在识别文字...', 5000)

    // 执行 OCR 识别（带进度回调）
    const result = await ocrService.recognize(dataUrl, (progress) => {
      console.log(`OCR 进度: ${progress.status} - ${Math.round(progress.progress * 100)}%`)
    })
    console.log('OCR 识别完成:', result)

    // 识别完成后，先清除所有旧的 toast（包括"正在识别文字..."的 toast）
    toast.clear()

    if (result.text.trim()) {
      // 显示结果对话框
      ocrResultText.value = result.text
      ocrConfidence.value = result.confidence
      ocrDialogVisible.value = true
      
      // 自动复制到剪贴板
      try {
        await navigator.clipboard.writeText(result.text)
        toast.success('识别完成！文字已自动复制到剪贴板', 2000)
      } catch (clipboardError) {
        console.error('自动复制失败:', clipboardError)
        toast.success('识别完成！请在对话框中复制文字', 2000)
      }
    } else {
      toast.warning('未识别到文字，请尝试选择包含清晰文字的区域', 3000)
    }
  } catch (error) {
    console.error('OCR 识别失败:', error)
    // 发生错误时也要清除旧的 toast
    toast.clear()
    const errorMsg = error instanceof Error ? error.message : String(error)
    toast.error(`OCR 识别失败：${errorMsg}`, 3000)
  }
}

// 处理 OCR 对话框的复制操作
const handleOCRCopy = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    toast.success(`已复制 ${text.length} 个字符到剪贴板`)
  } catch (error) {
    console.error('复制失败:', error)
    toast.error('复制失败，请手动复制')
  }
}

// 监听截图源数据
onMounted(async () => {
  // 直接显示组件
  isVisible.value = true
  
  // 等待 DOM 更新
  await nextTick()
  
  // 获取容器元素并聚焦（确保能捕获键盘事件）
  const container = document.querySelector('.screenshot-container') as HTMLElement
  if (container) {
    container.focus()
  }
  
  // 等待 Electron API 准备好（最多等 2 秒）
  console.log('检查 Electron API 是否准备好...')
  let retries = 40 // 40 次 * 50ms = 2 秒
  while (!window.electronAPI && retries > 0) {
    await new Promise(resolve => setTimeout(resolve, 50))
    retries--
  }
  
  if (!window.electronAPI) {
    console.warn('Electron API 未加载，请确保在 Electron 环境中运行')
    return // 直接返回，不继续执行
  }
  
  console.log('Electron API 已准备好')
  
  // 监听从主进程发来的截图数据
  window.electronAPI.onScreenshotSources((sources) => {
    if (sources.length > 0) {
      initialize(sources[0].thumbnail)
    }
  })
  
  // 主动请求截图数据
  try {
    const sources = await window.electronAPI.getScreenSources()
    if (sources.length > 0) {
      await initialize(sources[0].thumbnail)
    }
  } catch (error) {
    console.error('获取截图失败:', error)
    alert('获取屏幕截图失败，请重试')
  }

  // 监听键盘事件（使用 capture 模式确保能捕获）
  document.addEventListener('keydown', handleKeyDown, true)
})

onUnmounted(() => {
  if (window.electronAPI) {
    window.electronAPI.removeScreenshotSourcesListener()
  }

  document.removeEventListener('keydown', handleKeyDown, true)

  if (editor.value) {
    editor.value.destroy()
  }
})

// 暴露方法给父组件
defineExpose({
  initialize,
})
</script>

<style scoped>
.screenshot-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  cursor: crosshair;
  user-select: none;
  outline: none;
  overflow: hidden; /* 隐藏滚动条 */
}

.screenshot-canvas {
  position: fixed;
  top: 0;
  left: 0;
  cursor: crosshair;
  z-index: 1;
}

/* 简单的 Loading 提示 (暂时注释) */
/*
.loading-hint {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 16px 32px;
  border-radius: 8px;
  font-size: 16px;
  z-index: 10001;
  pointer-events: none;
}
*/

/* 暂时注释掉 Loading 功能，有问题需要重新设计 */
/*
.screenshot-canvas.canvas-disabled {
  pointer-events: none;
  opacity: 0.8;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-top-color: #00a8ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: white;
  font-size: 16px;
  font-weight: 500;
}
*/

.screenshot-selection {
  position: absolute;
  border: 2px solid #00a8ff;
  box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.5);
  pointer-events: none;
  z-index: 2;
  backdrop-filter: none; /* 确保选区内不模糊 */
}

.selection-info {
  position: absolute;
  top: -30px;
  left: 0;
  padding: 4px 8px;
  background-color: #00a8ff;
  color: white;
  font-size: 12px;
  border-radius: 4px;
  white-space: nowrap;
  pointer-events: none;
  z-index: 10001;
}

.toolbar-wrapper {
  pointer-events: auto;
  z-index: 10000;
}
</style>

